package org.ysu.shoeShopping.controller;

import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.ysu.shoeShopping.entity.Users;
import org.ysu.shoeShopping.service.UsersService;
import org.ysu.shoeShopping.utils.Result;

import java.util.List;
import java.util.Map;


/**
 * 前台用户表(Users)表控制层
 */
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    //登录
    @PostMapping("/login")
    public Result<Users> login(@RequestBody Users users){
        Users users1=usersService.findByUaccountAndUpwd(users.getUaccount(),users.getUpwd());
        if (users1 != null)
        {
            return Result.success(users1);
        }else {
            return Result.fail("2000","账号或者密码错误！！");
        }
    }
    @PostMapping("/register")
    public Result<String>register(@RequestBody Users users){
        if (usersService.findByUaccount(users.getUaccount()) != null)
        {
            usersService.insert(users);
            return Result.success("注册成功");
        }
        else{
            return Result.fail("201","账号已存在！！");
        }
    }
    //修改用户密码
    @PostMapping("/updatePassword")
    public Result<String> updateUserPassword(@RequestBody Map<String, Object> requestData){
        try {
            // 调试日志
            System.out.println("接收到的完整请求数据：" + requestData);

            // 从Map中提取数据，支持多种字段名
            Integer uid = null;
            String newPassword = null;
            String securityAnswer = null;

            // 调试：打印所有请求字段
            for (String key : requestData.keySet()) {
                System.out.println("请求数据字段: " + key + " = " + requestData.get(key));
            }

            // 尝试获取用户ID
            if (requestData.containsKey("uid")) {
                uid = (Integer) requestData.get("uid");
            } else if (requestData.containsKey("id")) {
                uid = (Integer) requestData.get("id");
            }

            // 尝试获取新密码
            if (requestData.containsKey("upwd")) {
                newPassword = (String) requestData.get("upwd");
            } else if (requestData.containsKey("password")) {
                newPassword = (String) requestData.get("password");
            } else if (requestData.containsKey("newPassword")) {
                newPassword = (String) requestData.get("newPassword");
            }

            // 尝试获取密保答案
            if (requestData.containsKey("upwdans")) {
                securityAnswer = (String) requestData.get("upwdans");
            } else if (requestData.containsKey("securityAnswer")) {
                securityAnswer = (String) requestData.get("securityAnswer");
            } else if (requestData.containsKey("answer")) {
                securityAnswer = (String) requestData.get("answer");
            } else if (requestData.containsKey("ans")) {
                securityAnswer = (String) requestData.get("ans");
            }

            System.out.println("解析后的数据 - UID: " + uid + ", 新密码: " + newPassword + ", 密保答案: " + securityAnswer);

            // 验证参数
            if (uid == null) {
                return Result.fail("400", "用户ID不能为空！");
            }
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return Result.fail("400", "密码不能为空！");
            }
            if (securityAnswer == null || securityAnswer.trim().isEmpty()) {
                System.out.println("密保答案为空，当前值: '" + securityAnswer + "'");
                return Result.fail("400", "密保答案不能为空！");
            }

            // 验证用户是否存在
            Users existingUser = usersService.findByUid(uid);
            if (existingUser == null) {
                return Result.fail("404", "用户不存在！");
            }

            // 验证密保答案（不需要验证密保问题，用户登录后前端已有密保问题）
            String dbSecurityAnswer = existingUser.getUpwdans();

            System.out.println("数据库中的密保答案: '" + dbSecurityAnswer + "'");
            System.out.println("用户输入的密保答案: '" + securityAnswer.trim() + "'");

            if (dbSecurityAnswer == null || !securityAnswer.trim().equals(dbSecurityAnswer.trim())) {
                System.out.println("密保答案验证失败");
                return Result.fail("401", "密保答案错误！");
            }

            System.out.println("密保答案验证通过，准备更新密码");

            // 密保验证通过，更新密码
            boolean success = usersService.updatePassword(uid, newPassword.trim());
            if (success) {
                return Result.success("密码修改成功！");
            } else {
                return Result.fail("500", "密码修改失败！");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印完整的异常堆栈
            return Result.fail("500", "系统错误：" + e.getMessage());
        }
    }

    //根据用户ID查询用户信息
    @GetMapping("/find/{id}")
    public Result<Users> findById(@PathVariable("id") Integer id) {
        try {
            Users user = usersService.findByUid(id);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.fail("404", "用户不存在");
            }
        } catch (Exception e) {
            return Result.fail("500", "查询用户信息失败: " + e.getMessage());
        }
    }

    //用户头像
// 查询所有用户
    @GetMapping("/find/all")
    public Result<List<Users>> findAllUsers() {
      List<Users> users = usersService.findAllUsers();
        if (users == null) {
            // 如果没有找到用户，返回失败
            return Result.fail("404", "没有找到用户");
        }
        // 如果查询到了用户，返回成功
        return Result.success(users);
    }
    //更新用户信息
    @PostMapping("/updateUserInfo")
    public Result<String> updateUserInfo(@RequestBody Users users) {
        Users users1 = usersService.findByUid(users.getUid());
        if (users1 == null) {
            // 如果没有找到用户，返回失败
            return Result.fail("404", "没有找到用户");
        }else {
            usersService.update(users);
            return Result.success("更新成功");
        }
    }

    @PostMapping("/addUsers")
    public Result<String> addUsers(@RequestBody Users users) {
        Users users1= usersService.insert(users);
        if (users1 == null) {
            // 如果没有找到用户，返回失败
            return Result.fail("404", "新增用户失败");
        }else {
            return Result.success("更新成功");
        }
    }



}



